﻿using System;
using System.Collections.Generic;
using System.Threading;


namespace WAF.Server.Sessions
{
    public class Session : IDisposable
    {

        static AutoResetEvent processQueueEvent = new AutoResetEvent(false);
        static Thread disposingWorkerTread;
        static volatile bool stopDisposingThreadFlag = false;

        static Session()
        {
        }

        #region Session Container

        static Dictionary<byte[], Session> sessions = new Dictionary<byte[], Session>(new KeyComparer());
        static LinkedList<Session> sessionLastAcessList = new LinkedList<Session>();
        static object sessionsLock = new object();

        public static void AddSession(Session session)
        {
            session.SessionStarted = unchecked((uint)Environment.TickCount);
            session.SessionLastValidated = unchecked((uint)Environment.TickCount);

            lock (sessionsLock)
            {
                try
                {
                    sessions.Add(session.ID, session);
                    sessionLastAcessList.AddLast(session);
                }
                catch (Exception )
                {
                    // TODO: Log Errors
                    foreach (Session se in sessions.Values)
                    {
                        if (se.ID[0] == session.ID[0])
                        {
                            Console.WriteLine("Session:" + se.ToString());
                        }
                    }
                }
            }
        }

        public static void RemoveSession(byte[] id)
        {
            lock (sessionsLock)
            {
                sessions.Remove(id);
            }
        }

        public static Session ValidateSession(byte[] id)
        {
            if (id == null || id.Length != 32)
                return null;

            var session = GetSession(id);
            if (session == null)
                return null;

            session.SessionLastValidated = ((uint)Environment.TickCount);
            lock (sessionsLock)
            {
                sessionLastAcessList.Remove(session);
                sessionLastAcessList.AddLast(session);
            }

            return session;

        }


        static Session GetSession(byte[] id)
        {
            Session result = null;
            lock (sessionsLock)
            {
                sessions.TryGetValue(id, out result);
            }
            return result;
        }
        #endregion

        #region Session Disposing

        static public void StartSessionDisposing()
        {
            disposingWorkerTread = new Thread(DisposingWorkerTread);
            disposingWorkerTread.Start();
        }

        static public void StopSessionDisposing()
        {
            stopDisposingThreadFlag = true;
            processQueueEvent.Set();
            disposingWorkerTread.Join(500);
            if (disposingWorkerTread.IsAlive)
            {
                disposingWorkerTread.Abort();
                disposingWorkerTread.Join();
            }
        }

        static void DisposingWorkerTread()
        {
            while (true)
            {
                processQueueEvent.WaitOne(1000);

                while (true)
                {
                    if (stopDisposingThreadFlag)
                        return;

                    var now = ((uint)Environment.TickCount);

                    Session sessionToDispose = null;
                    lock (sessionsLock)
                    {
                        if (sessionLastAcessList.Count == 0)
                            break;

                        sessionToDispose = sessionLastAcessList.First.Value;

                        if (now - sessionToDispose.SessionLastValidated < 20000)
                            break;

                        sessions.Remove(sessionToDispose.ID);
                        sessionLastAcessList.RemoveFirst();
                    }
                    sessionToDispose.Dispose();
                }


            }

        }
        #endregion


        byte[] id;
        uint SessionStarted { get; set; }
        uint SessionLastValidated { get; set; }

        public Session(byte[] id)
        {
            this.id = id;
        }


        public byte[] ID { get { return id; } }

        public class KeyComparer : IEqualityComparer<byte[]>
        {
            public bool Equals(byte[] firstKey, byte[] secondKey)
            {
                if (firstKey == null || secondKey == null)
                    throw new ArgumentNullException();

                if (firstKey.Length != 32 || secondKey.Length != 32)
                    throw new ArgumentOutOfRangeException("Keys must have a length of 32 bytes");

                for (int index = 0; index < 32; ++index)
                {
                    if (firstKey[index] != secondKey[index])
                        return false;
                }

                return true;
            }

            public int GetHashCode(byte[] key)
            {
                if (key == null)
                    throw new ArgumentNullException();

                if (key.Length != 32)
                    throw new ArgumentOutOfRangeException("Keys must have a length of 32 bytes");

                uint returnValue = ((uint)key[0]) << 24;
                returnValue ^= ((uint)key[1]) << 16;
                returnValue ^= ((uint)key[2]) << 8;
                returnValue ^= ((uint)key[3]);

                return unchecked((int)returnValue);

            }
        }

        public bool IsDisposed { get { return ID == null; } }

        ~Session() { Dispose(false); }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }


        void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                id = null;
            }
        }




        public override string ToString()
        {
            return "Session: " + Convert.ToBase64String(ID);
        }



    }

}